package com.ht.api.call.func.impl.wwx;

import javax.sql.DataSource;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.constant.CustomerLinkStatus;
import com.ht.api.db.Db;
import com.ht.api.db.Entity;
import com.ht.api.db.exception.HtException;
import com.ht.api.db.util.HtUtil;
import com.ht.api.open.OpenUtil;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
/**
 * 获客链接切换状态
 * @author asq
 * @createTime 2025年1月13日 22:19:08
 */
@Slf4j
public class WwxCustomerLinkStatusChangeEditFunctionCall implements IFunctionCall {
	/** 接口ID：创建获客链接 */
	private static final long API_ID_ADD = 1896832030612787200L;
	/** 接口ID：删除获客链接 */
	private static final long API_ID_DEL = 1896834425233215488L;

	@Override
	public String getName() {
		return "获客链接切换状态";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		// 获取登陆用户的数据源
		DataSource ds = me.getDataSource();
		
		// 验证参数
		HtUtil.checkParam(param, "main_id", "status");
		
		// 查询获客链接
		String mainId = param.getStr("main_id");
		int newStatus = param.getInt("status");
		Entity wxCustomerLink = Db.createSqlParser("wx_customer_link").findById(ds, mainId);
		if (wxCustomerLink == null) {
			throw new HtException("获客链接不存在~");
		}
		if (wxCustomerLink.getInt("status") == newStatus) {
			throw new HtException("请指定新的状态~");
		}
		
		// 根据新状态值，来决定具体操作
		switch (newStatus) {
		case CustomerLinkStatus.ENABLED:
			enabled(ds, wxCustomerLink);
			break;
			
		case CustomerLinkStatus.PAUSE:
			parse(ds, wxCustomerLink);
			break;
			
		case CustomerLinkStatus.DISABLED:
			disabled(ds, wxCustomerLink);
			break;

		default:
			break;
		}
		
		return JSONUtil.createObj();
	}
	
	/**
	 * 启用
	 * @param ds
	 * @param wxCustomerLink
	 */
	private void enabled(DataSource ds, Entity wxCustomerLink) {
		boolean needSynWx = StrUtil.isBlank(wxCustomerLink.getStr("link_id"));
		if (needSynWx) {
			// 防止没有绑定客服人员的时候去启用
			JSONArray userArr = wxCustomerLink.getJSONArray("user_list");
			if (userArr == null || userArr.isEmpty()) {
				throw new HtException("请绑定客服之后再启用~");
			}
			
			// 调用企微接口，新增
			String appId = wxCustomerLink.getStr("appid");
			JSONObject wwxParam = JSONUtil.createObj();
			wwxParam.set("link_name", wxCustomerLink.getStr("link_name"));
			wwxParam.set("range.user_list", JSONUtil.parseArray(wxCustomerLink.getStr("user_list")));
			wwxParam.set("skip_verify", wxCustomerLink.getInt("skip_verify") == 1);
			if (wxCustomerLink.containsKey("priority_option")) {
				wwxParam.set("priority_option.priority_type", wxCustomerLink.getInt("priority_type"));
				wwxParam.set("priority_option.priority_userid_list", JSONUtil.parseArray(wxCustomerLink.getStr("priority_userid_list")));
			}
			String str = OpenUtil.call(appId, API_ID_ADD, wwxParam);
			
			// 本地数据库
			JSONObject obj = JSONUtil.parseObj(str);
			if (obj.getInt("errcode") == 0) {
				JSONObject wxLink = obj.getJSONObject("link");
				wxCustomerLink.set("status", CustomerLinkStatus.ENABLED);
				wxCustomerLink.set("link_id", wxLink.getStr("link_id"));
				wxCustomerLink.set("url", wxLink.getStr("url"));
				wxCustomerLink.set("create_time", HtUtil.formatTimeString(wxLink.getStr("create_time")));
				Db.insert(ds, wxCustomerLink);
			} else {
				throw new HtException("企微接口返回错误：" + obj.getStr("errmsg"));
			}
		} else {
			wxCustomerLink.set("status", CustomerLinkStatus.ENABLED);
			Db.insert(ds, wxCustomerLink);
		}
	}
	
	/**
	 * 暂停
	 * @param ds
	 * @param wxCustomerLink
	 */
	private void parse(DataSource ds, Entity wxCustomerLink) {
		wxCustomerLink.set("status", CustomerLinkStatus.PAUSE);
		Db.insert(ds, wxCustomerLink);
	}
	
	/**
	 * 停用
	 * @param ds
	 * @param wxCustomerLink
	 */
	private void disabled(DataSource ds, Entity wxCustomerLink) {
		boolean needSynWx = StrUtil.isNotBlank(wxCustomerLink.getStr("link_id"));
		if (needSynWx) {
			// 调用企微接口，删除
			String appId = wxCustomerLink.getStr("appid");
			JSONObject wwxParam = JSONUtil.createObj().set("link_id", wxCustomerLink.getStr("link_id"));
			String str = OpenUtil.call(appId, API_ID_DEL, wwxParam);
			
			// 本地数据库
			JSONObject obj = JSONUtil.parseObj(str);
			if (obj.getInt("errcode") == 0) {
				wxCustomerLink.set("status", CustomerLinkStatus.DISABLED);
				wxCustomerLink.set("link_id", "");
				wxCustomerLink.set("url", "");
				wxCustomerLink.set("create_time", "");
				Db.insert(ds, wxCustomerLink);
			} else {
				throw new HtException("企微接口返回错误：" + obj.getStr("errmsg"));
			}
		} else {
			wxCustomerLink.set("status", CustomerLinkStatus.DISABLED);
			Db.insert(ds, wxCustomerLink);
		}
	}
}
